import os
import sys
import logging
from logging.handlers import TimedRotatingFileHandler

from framework.constant.SysConstant import SysConstant


class LogComponent:

    def __init__(self, name, level=logging.DEBUG):
        self._name = name
        self._level = level
        self._fmt = '[%(asctime)s] %(levelname)s in %(module)s %(funcName)s %(thread)d:\n-> %(message)s'
        #'%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
        self._default_logger = logging.getLogger(name)
        self._default_logger.level = level

        console_handler = logging.StreamHandler()
        console_handler.setLevel(level)
        console_handler.setFormatter(logging.Formatter(self._fmt))
        console_handler.setStream(sys.stdout)
        self._default_logger.addHandler(console_handler)

        if '/data/deploy' in sys.path[0]:
            filename = os.path.join(SysConstant.logs_path, 'app.log')
            timed_rotating_file_handler = TimedRotatingFileHandler(filename=filename, when='D', interval=1, backupCount=60)
            timed_rotating_file_handler.setLevel(level)
            timed_rotating_file_handler.setFormatter(logging.Formatter(self._fmt))
            self._default_logger.addHandler(timed_rotating_file_handler)

    def get_logger(self) -> logging.Logger:
        return self._default_logger

